﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	[DefaultProperty("Digit")]
	[ToolboxData("<{0}:MyMobileNumberValidator runat=\"server\"></{0}:MyMobileNumberValidator>")]
	public sealed class MyMobileNumberValidator : MyFormatBaseValidator {
		/// <summary>
		/// 
		/// </summary>
		private const int DefaultCountryNumberDigit = 4;

		/// <summary>
		/// 
		/// </summary>
		private const int DefaultDigit = 11;

		/// <summary>
		/// 
		/// </summary>
		private const string DefaultPrefixNumber = "13,15,18";

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(false)]
		[Browsable(true)]
		[DefaultValue(DefaultCountryNumberDigit)]
		public int CountryNumberDigit {
			get {
				var v = ViewState["CountryNumberDigit"];
				if (v == null) {
					return DefaultCountryNumberDigit;
				} else {
					return (int)v;
				}
			}
			set {
				if (value < 0) {
					throw new ArgumentOutOfRangeException("Value of CountryNumberDigit cannot less than 0, bus was " + value);
				}

				ViewState["CountryNumberDigit"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(false)]
		[Browsable(true)]
		[DefaultValue(DefaultPrefixNumber)]
		public string PrefixNumber {
			get {
				var v = ViewState["PrefixNumber"];
				if (v == null) {
					return DefaultPrefixNumber;
				} else {
					return (string)v;
				}
			}
			set {
				ViewState["PrefixNumber"] = value == null ? "" : value.Trim();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		[Category("Appearance")]
		[Bindable(false)]
		[Browsable(true)]
		[DefaultValue(DefaultDigit)]
		public int Digit {
			get {
				var v = ViewState["Digit"];
				if (v == null) {
					return DefaultDigit;
				} else {
					return (int)v;
				}
			}
			set {
				if (value < 1) {
					throw new ArgumentOutOfRangeException("Value of Digit cannot less than 1, bus was " + value);
				}

				ViewState["Digit"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected override string GetExpression() {
			var exp = new System.Text.StringBuilder();

			if (CountryNumberDigit > 0) {
				exp.AppendFormat(@"(\d{{1,{0}}}\-)?", CountryNumberDigit);
			}

			if (!string.IsNullOrWhiteSpace(PrefixNumber)) {
				var prefixNumberArray = PrefixNumber.Split(',').Each(pn => pn.Trim()).ToArray();
				var l = prefixNumberArray[0].Length;
				exp.AppendFormat(@"(({1})\d{{{0}}})", Digit - l, string.Join("|", prefixNumberArray));
			} else {
				exp.AppendFormat(@"(\d{{{0}}})", Digit);
			}

			return exp.ToString();
		}
	} // end of MyEmailValidator.
}
